﻿// Allows the item or items of a container to be activated (tab, accordion, wizard, etc)
define([
    'Wjs/Wjs'
],
function () {
    'use strict';

    return Wjs.defineOnce({

        type: 'Activatable',

        internal: {

            initialize: function () {

                this.activeItem = 0; // Activate the first item by default
            },

            listeners: {

                onDomElementCreated: function () {
                    var activeItem = this.activeItem;

                    this.activeItem = null; // Nullify it so it does not get deactivated

                    this.activate(activeItem, 'first');
                }
            }
        },

        onActivate: function(fcn) {

            this.activatehandler = Wjs.chain(this.activatehandler, fcn);

            return this;
        },

        onDeactivate: function(fcn) {

            if (this.deactivatehandler) {

                Wjs.log('warn', 'Replacing deactivation handler');
            }

            this.deactivatehandler = fcn; // Do not chain since the function returns a cancellation value

            return this;
        },

        activate: function (item, activationType) {
            var activeItem = this.getActiveItem();

            item = Wjs.isNumber(item) ? this.getItem(item) : item;

            if (activeItem === item) {

                console.log("Item is already active");

                return;
            }

            if (activeItem) {

                if (this.deactivate(activeItem, activationType) === false) { // Cancelling the deactivation also cancels activating the new item

                    return;
                }
            }

            this.activeItem = item;

            if (item && this.activateHandler) {

                this.activateHandler(item, activationType);
            }
        },

        deactivate: function (item, activationType) {

            if (this.deactivateHandler) {

                return this.deactivateHandler(item, activationType); // Cancelling the deactivation also cancels activating the new item
            }
        },

        getActiveItem: function () {
            var item = this.activeItem;

            return Wjs.isNumber(item) ? this.getItem(item) : item;
        }

    });

});